import { defineConfig, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import configContent from './vite.object.config'

const path = require('path')
const fs = require('fs')
const os = require('os')

const resolve = dir => path.join(__dirname, dir)
const getIPAdress = () => {
  let ip: string = '127.0.0.1'
  try {
    const address = os.networkInterfaces()
    Object.keys(address).forEach(key => {
      address[key].forEach(el => {
        if (el.family === 'IPv4' && el.address !== '127.0.0.1' && !el.internal) {
          ip = el.address
        }
      })
    })
  } catch (error) {
    // eslint-disable-next-line no-console
    console.error('error:', error)
  }
  return ip
}

// 初始化变量
let layoutObject: any = ''

// 获取layout名称
const layoutTemolate = configContent.envConfig.VITE_APP_CURRENT_LAYOUT
if (!layoutTemolate) throw Error('未选择布局模板')
// 通过layout名称匹配layout对象
configContent.layoutConfig.forEach(el => {
  if (el.fileName === layoutTemolate) {
    layoutObject = el
  }
})
if (!layoutObject) throw Error('选择布局模板不存在')
// 判断是否开启页面缩放功能
if (!layoutObject.openZoom) {
  configContent.envConfig.VITE_APP_AUTO_ZOOM = false
  configContent.envConfig.VITE_APP_ZOOM_BUTTON = false
}

// 对象转字符串
Object.keys(configContent.envConfig).forEach(key => {
  if (typeof configContent.envConfig[key] === 'object') {
    configContent.envConfig[key] = JSON.stringify(configContent.envConfig[key])
  }
})

// 注入env
process.env = Object.assign(process.env, configContent.envConfig, process.env.BABEL_ENV === 'development' ? configContent.developmentConfig : configContent.productionConfig)

// 编辑文件
fs.readFile(path.resolve(__dirname, './src/styles/variable.scss'), (err, scssFile) => {
  if (err) throw err
  let scssFileContent
  scssFileContent = scssFile.toString()
  // 处理布局模式设置
  // 处理模块隐藏样式调整
  scssFileContent = scssFileContent.replace(
    /\$maincontent_height:calc\(.+\)/,
    `$maincontent_height:calc(100% - 
    ${configContent.envConfig.VITE_APP_BREADCRUMB_SHOW ? '#{$breadcrumb_height} - ' : ''}
    ${configContent.envConfig.VITE_APP_TAGSVIEW_SHOW ? '#{$tagsview_height} - ' : ''}#{$maincontent_to_botton_size})`
  )
  fs.writeFileSync(path.resolve(__dirname, './src/styles/variable.scss'), scssFileContent)
})
fs.readFile(path.resolve(__dirname, './index.html'), (err, scssFile) => {
  if (err) throw err
  let htmlFileContent
  htmlFileContent = scssFile.toString()
  // 处理布局模式设置
  // 处理模块隐藏样式调整
  htmlFileContent = htmlFileContent.replace(/<title>.+<\/title>/, `<title>${configContent.objectName}</title>`)
  fs.writeFileSync(path.resolve(__dirname, './index.html'), htmlFileContent)
})

export default ({ mode }) => {
  const options = {
    plugins: [
      vue(),
      Components({
        resolvers: [ElementPlusResolver()]
      })
    ],
    base: './',
    server: {
      host: getIPAdress(),
      open: false
    },
    resolve: {
      alias: [
        {
          find: '@',
          replacement: resolve('./src')
        },
        {
          find: 'assets',
          replacement: resolve('./src/assets')
        },
        {
          find: 'components',
          replacement: resolve('./src/components')
        },
        {
          find: 'interfaces',
          replacement: resolve('./src/interfaces')
        },
        {
          find: 'plugins',
          replacement: resolve('./src/plugins')
        }
      ]
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/styles/variable.scss";'
        }
      }
    },
    build: {
      target: 'modules',
      outDir: mode === 'production' ? configContent.productionConfig.outputDir : configContent.developmentConfig.outputDir,
      sourcemap: !(mode === 'production')
    }
  } as UserConfig
  return defineConfig(options)
}
